# !/usr/bin/env python
# -*-coding:utf-8 -*-

"""
# Author     ：skyTree
# version    ：python 3.11
# Description：菜单视图
"""
from flask import request
from api.models import Menu
from api.menu import menu_api
from api.utils.response import to_response
from api.utils.baseResource import BaseResource


class MenuResource(BaseResource):
    def get(self):
        type = request.args.get('type', None)
        if not type or type not in ['list', 'tree']:
            return to_response(10000, msg='参数不全，或参数错误！')

        if type == 'list':
            menus = Menu.query.filter(Menu.level != 0).all()
            return to_response(200, data=[menu.to_dict() for menu in menus])
        menu_list = Menu.query.filter(Menu.level != 0).all()
        menu_dict = [m.to_dict() for m in menu_list]
        tree = []
        if type == 'tree':
            for m in menu_dict:
                if m['level'] == 1:
                    m['children'] = []
                    tree.append(m)
                else:
                    for t in tree:
                        if t['id'] == m['pid']:
                            t['children'].append(m)
                            break
        return to_response(200, data=tree)


menu_api.add_resource(MenuResource, '/menu')
